home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 14203 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.9 KB  |  79 lines

  1. Path: user2.mnsinc.com!huang
  2. From: huang@mnsinc.com (Szu-Wen Huang)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Can anyone help a newbie out ?
  5. Date: 12 Apr 1996 14:57:47 GMT
  6. Organization: Monumental Network Systems
  7. Message-ID: <4klr1b$29d@news1.mnsinc.com>
  8. References: <4kkf3r$5b0@darwin.nbnet.nb.ca>
  9. NNTP-Posting-Host: user.mnsinc.com
  10. X-Newsreader: TIN [version 1.2 PL2]
  11.  
  12. Jeff (lewwid@brunswickmicro.nb.ca) wrote:
  13.  
  14. : Problem:Write a function that accepts two strings.  Count the number
  15. : of characters in each string, and return the pointer to the longer
  16. : string.
  17.  
  18. Rule #1:  learn thy standard libraries and thy miseries will end.  Look
  19. up on 'strlen()'.  :)
  20.  
  21. [snip]
  22. : /* Checksize .. checks to see which array of char is longer, and
  23. : returns the longest of the 2 */
  24. : char checksize(char x[], char y[])
  25. : {
  26. :     int count, int total = 0, int total1 = 0;
  27.  
  28. :     while (*x != NULL)
  29. :         total += 1
  30.  
  31. 1.  Won't compile because you are missing a semicolon
  32. 2.  Since x is a char[], *x is a char.  NULL is a pointer.  You should
  33.     use a 0, or better yet, '\0' because you're looking for the null
  34.     terminator of the ASCIIZ string.
  35. 3.  Note that x never changes.  You're always checking the first character
  36.     of x[].
  37. *.  (stylistic) "+= 1" is probably easier to read if written as "++".
  38. *.  A good programmer will check if x is NULL first.
  39.  
  40. Now, putting that all together,
  41.  
  42. char *s;
  43.  
  44. if (x != NULL) {
  45.   s = x;
  46.   while (*s != '\0') {
  47.     total++;
  48.     s++;
  49.   }
  50. }
  51.  
  52. (Note that you can also write the loop as:)
  53.  
  54. while (*s++ != '\0')
  55.   total++;
  56.  
  57. (or better yet)
  58.  
  59. total = strlen(x);
  60.  
  61. :     while (*y != NULL)
  62. :         total1 += 1
  63.  
  64. :     if (total < total2)
  65. :         return *y;
  66. :     if (total > total2)
  67. :         return *x;
  68.  
  69. *y and *x are characters.  Your declaration said to return characters,
  70. but your specification said to return a pointer to the characters.  You'll
  71. want to change it to:
  72.  
  73. char *checksize(char x[], char y[])
  74.  
  75. and return x or y.  Hth.
  76.  
  77. :}
  78.  
  79.